package com.gezi.admin.module.app.resource;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gezi.admin.config.application.ApplicationUtil;
import com.gezi.admin.config.exception.type.ApiException;
import com.gezi.admin.module.app.file.AppFileUtil;
import com.gezi.admin.module.app.file.model.AppFileInfoModel;
import com.gezi.admin.module.config.BaseController;
import com.gezi.admin.module.config.utils.PageUtil;
import com.gezi.admin.module.config.utils.PageVo;
import com.gezi.admin.security.SecurityUtil;
import com.gezi.admin.security.annotation.SecurityIgnoreUrl;
import com.gezi.admin.module.app.resource.model.AppResourceAddParamModel;
import com.gezi.admin.module.app.resource.model.AppResourceEditParamModel;
import com.gezi.admin.module.app.resource.model.AppResourceSearchModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotBlank;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author 格子软件
 * @createDate 2024/2/10 09:00
 * @contact 公众号：格子软件 微信：13716343106 邮箱：1424529270@qq.com
 */
@Slf4j
@Api(tags = "资源管理")
@RestController
@RequestMapping("api/app/resource")
public class AppResourceController extends BaseController {

    @Resource
    private AppResourceService appResourceService;

    @ApiOperation("查询分页")
    @GetMapping(value = "/findAllByPage")
    public Object findAllByPage(PageVo page, AppResourceSearchModel searchVo) {
        Page<Map> pageData = appResourceService.findByPage(PageUtil.initMpPage(page),searchVo);
        return pageData;
    }

    @ApiOperation("查询列表")
    @GetMapping(value = "/findAllByList")
    public Object findAllByList(AppResourceSearchModel searchVo) {
        String userId = SecurityUtil.getUserId();
        searchVo.setUserId(userId);
        List<Map> list = appResourceService.findByList(searchVo);
        return list;
    }

    @ApiOperation("查询详情")
    @GetMapping(value = "/findById/{id}")
    public Map findById(@PathVariable @NotBlank(message = "参数不能为空")String id) {
        AppResourceEntity appResourceEntity = appResourceService.getById(id);
        if(appResourceEntity == null){
            throw ApiException.getInstance("数据不存在，请刷新重试");
        }

        Map result = JSON.parseObject(JSON.toJSONString(appResourceEntity),Map.class);

        return result;
    }

    @ApiOperation("查询通过类型")
    @SecurityIgnoreUrl
    @GetMapping(value = "/findByType/{type}")
    public void findByType(@PathVariable String type, HttpServletResponse response) throws IOException {
        AppResourceEntity appResourceEntity = appResourceService.findByName(type);
        if(appResourceEntity == null){
            throw ApiException.getInstance("数据不存在，请刷新重试");
        }
        response.sendRedirect(appResourceEntity.getUrl());
    }

    @ApiOperation("添加")
    @PostMapping(value = "/add")
    public void add(@Validated @RequestBody AppResourceAddParamModel paramModel) {
        if(FileNameUtil.containsInvalid(paramModel.getName())){
            throw ApiException.getInstance("资源名字中包含非法字符");
        }
        //名字不能相同
        AppResourceEntity appResourceEntity = appResourceService.findByName(paramModel.getName());
        if(appResourceEntity != null){
            throw ApiException.getInstance("资源名称已存在");
        }
        appResourceEntity = new AppResourceEntity();
        appResourceEntity.setData(paramModel);
        //修改文件名称
        AppFileInfoModel appFileInfoModel = AppFileUtil.getFileInfoByUrl(paramModel.getUrl());
        File reFile = FileUtil.rename(appFileInfoModel.getFile(),paramModel.getName(),true,true);
        appResourceEntity.setUrl(AppFileUtil.getUrlByFile(reFile));
        appResourceService.save(appResourceEntity);
    }

    @ApiOperation("修改")
    @PostMapping(value = "/edit")
    public void edit(@Validated @RequestBody AppResourceEditParamModel paramModel) {
        if(FileNameUtil.containsInvalid(paramModel.getName())){
            throw ApiException.getInstance("资源名字中包含非法字符");
        }
        //校验参数
        AppResourceEntity appResourceEntity = appResourceService.getById(paramModel.getId());
        if(appResourceEntity == null){
            throw ApiException.getInstance("数据不存在，请刷新重试");
        }
        appResourceEntity.setData(paramModel);
        AppFileInfoModel appFileInfoModel = AppFileUtil.getFileInfoByUrl(paramModel.getUrl());
        File reFile = FileUtil.rename(appFileInfoModel.getFile(),paramModel.getName(),true,true);
        appResourceEntity.setUrl(AppFileUtil.getUrlByFile(reFile));
        appResourceService.saveOrUpdate(appResourceEntity);
    }

    @ApiOperation("删除")
    @DeleteMapping(value = "/delByIds/{ids}")
    public void delById(@PathVariable String[] ids) {
        appResourceService.removeByIds(Arrays.asList(ids));
    }
}